package com.situ.ymall.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.situ.ymall.admin.intercepter.RootIntercepter;

/**
 * 相当于原来的springmvc的配置文件
 * 
 * @author 小飞
 *
 */
@Configuration
public class webConfig implements WebMvcConfigurer{
	
	@Value("${spring.servlet.multipart.location}")
	private String path;
	@Autowired
	private RootIntercepter rootIntercepter;
	
	//静态资源路径映射
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		
		registry.addResourceHandler("/upload/**")
			.addResourceLocations("file:"+path);
	}
	
	// 配置拦截器
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(rootIntercepter)
			.addPathPatterns("/**")
			.excludePathPatterns("/api/roots","/vercode/**","/vercode", "/upload/**","/api/goods");
	}
	
	@Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");	// 允许的域
        //config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("token");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

}
